#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

LNode* BuyLTNode(LTDatatype x)
{
	LNode* newnode = (LNode*)malloc(sizeof(LNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

LNode* LTInit()
{
	LNode* phead = BuyLTNode(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void LTPustBack(LNode* phead, LTDatatype x)
{
	assert(phead);
	LNode* tail = phead->prev;
	LNode* newnode = BuyLTNode(x);

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}
void LTPrint(LNode* phead)
{
	assert(phead);
	LNode* cur = phead->next;
	printf("phead<==>");
	while (cur != phead)
	{
		printf("%d<==>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

//void LTPustFront(LNode* phead, LTDatatype x)
//{
//	assert(phead);
//	LNode* newnode = BuyLTNode(x);
//	newnode->next = phead->next;
//	phead->next->prev = newnode;
//	phead->next = newnode;
//	newnode->prev = phead;
//
//}
void LTPustFront(LNode* phead, LTDatatype x)
{
	assert(phead);
	LNode* newnode = BuyLTNode(x);
	LNode* first = phead->next;
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = first;
	first->prev = newnode;
}
void LTPopBack(LNode* phead)
{
	assert(phead);
	LNode* tail = phead->prev;
	LNode* tailprev = tail->prev;
	free(tail);
	phead->prev = tailprev;
	tailprev->next = phead;
}

void LTPopFront(LNode* phead)
{
	assert(phead);
	LNode* first = phead->next;
	LNode* second = first->next;
	phead->next = second;
	second->prev = phead;
	free(first);
}

LNode* LTFind(LNode* phead, LTDatatype x)
{
	assert(phead);
	LNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void LTInsert(LNode* pos, LTDatatype x)
{
	assert(pos);
	LNode* prev = pos->prev;
	LNode* newnode = BuyLTNode(x);

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LNode* pos)
{
	assert(pos);
	LNode* tail = pos->next;
	LNode* prev = pos->prev;
	prev->next = tail;
	tail->prev = prev;
}


